package com.ruijie.autotest.log.common.crypto;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class CBC implements CipherInitializer {

	private final SecretKey secretKey;

	private final String ivPassword;

	private final String pattern;

	private CBC(SecretKey secretKey, String ivPassword, String pattern) {
		this.secretKey = secretKey;
		this.ivPassword = ivPassword;
		this.pattern = pattern;
	}

	@Override
	public Cipher createCipher(int cryptoMode) {
		try {
			Cipher result = Cipher.getInstance(pattern);
			result.init(cryptoMode, secretKey, new IvParameterSpec(ivPassword.getBytes()));
			return result;
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
			throw new RuntimeException("failed to create cipher. ", e);
		}
	}

	public static CBC create(Algorithm algorithm, String password, String ivPassword, String paddingName) {
		return new CBC(algorithm.createSecretKey(password),
				ivPassword,
				algorithm.patternOf("CBC", paddingName));
	}
}
